<template>
  <div class="app-car-container">
    <CustomContent>
      <template v-slot:body>
        <div>
          <el-form :model="$data" label-width="160px" label-position="right" size="small" ref="MmvAddForm" inline>
            <el-row :gutter="15">
              <el-row>
                <el-col :span="24">
                  <MmvTitle title="客户信息"></MmvTitle>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="选择客户" required>
                    <div style="display: inline-block" @click="showkehu = true">
                      <el-input :value="kehu.memberName" style="width: 220px; margin-right: 15px" placeholder="请选择客户"
                                readonly>
                        <el-button icon="el-icon-search" slot="append" @click="showkehu = true"></el-button>
                      </el-input>
                    </div>

                    <div style="display: inline-block">
                      未找到客户?
                      <el-button type="text" @click="openCustomer = true">点击立即添加
                      </el-button>
                    </div>
                  </el-form-item>
                </el-col>
                <template v-if="kehu.memberNo">
                  <el-col :sm="12" :md="8">
                    <el-form-item label="客户类型">{{
                        kehu.memberType | memberType
                      }}
                    </el-form-item>
                  </el-col>

                  <el-col :sm="12" :md="8" v-if="kehu.memberType == 1">
                    <el-form-item label="企业联系人">{{
                        kehu.contactMember || '--'
                      }}
                    </el-form-item>
                  </el-col>
                  <el-col :sm="12" :md="8">
                    <el-form-item label="客户来源">
                      <dict-tag
                        :options="dict.type.memberSource"
                        :value="kehu.memberSource"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :sm="12" :md="8">
                    <el-form-item label="证件号码">{{
                        kehu.cardId || '--'
                      }}
                    </el-form-item>
                  </el-col>
                  <el-col :sm="12" :md="8">
                    <el-form-item label="联系方式">{{
                        kehu.contactPhone || '--'
                      }}
                    </el-form-item>
                  </el-col>
                  <el-col :sm="12" :span="24">
                    <el-form-item label="联系地址">{{ kehu.contactAddress || '--' }}
                    </el-form-item>
                  </el-col>
                </template>
              </el-row>
              <!-- 添加或修改会员基础信息对话框 -->
              <el-dialog title="添加会员" :visible.sync="openCustomer" width="1100px" destroy-on-close append-to-body>
                <MmvAdd ref="MmvAdd" v-if="openCustomer" :editid="null"></MmvAdd>
                <div slot="footer">
                  <el-button @click="openCustomer = false">取消</el-button>
                  <el-button type="primary" @click="submitForm" :loading="submitLoading">确定
                  </el-button>

                </div>
              </el-dialog>

              <el-col :span="24">
                <MmvTitle title="预定信息"></MmvTitle>
              </el-col>
              <el-row v-if="!orderNo">
                <el-form-item label="订单号">
                  <div style="display: flex;width: 100%">
                    <div style="width: 200px;flex: 1">
                      <el-switch v-model="addOrSub" active-text="自定义" inactive-text="系统生成" :active-value='2' :inactive-value='1' @change="myOrderNo=null"></el-switch>
                    </div>
                    <div style="width: 200px;flex: 1">
                      <el-input v-model="myOrderNo" placeholder="自定义订单编号" v-if="addOrSub==2" :disabled="orderNo"></el-input>
                    </div>
                  </div>
                </el-form-item>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="取车类型" required>
                    <el-radio-group v-model="rentalType" style="width: 100%" @change="clearChexin">
                      <el-radio :label="1">到店取还车</el-radio>
                      <!-- <el-radio :label="2">自助取还车</el-radio> -->
                      <el-radio :label="3">上门送取车</el-radio>
                      <el-radio :label="4">上门送车</el-radio>
                      <el-radio :label="5">上门取车</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12" v-if="rentalType == 3 || rentalType == 4">
                  <el-form-item label="取车地址" prop="storeLon">
                    <el-input v-model="takeAddress" placeholder="请地图选点" :readonly="takeAddressReadonly">
                      <el-button icon="el-icon-search" slot="append" @click="positionShow = true"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="rentalType == 3 || rentalType == 5">
                  <el-form-item label="还车地址" prop="storeLon">
                    <el-input v-model="alsoAddress" placeholder="请地图选点" :readonly="alsoAddressReadonly">
                      <el-button icon="el-icon-search" slot="append" @click="positionShow2 = true"></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="取车门店" required>
                    <div style="display: flex">
                      <el-input :value="quchemendian.storeName"
                                @click.native="handleChooseStore(1)" readonly
                                placeholder="请选择门店">
                        <el-button icon="el-icon-search" slot="append" @click="handleChooseStore(1)"></el-button>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="还车门店" required>
                    <div style="display: flex">
                      <el-input :value="huanchemendian.storeName"
                                @click.native="handleChooseStore(2)" readonly
                                placeholder="请选择门店">
                        <el-button icon="el-icon-search" slot="append"
                                   @click="handleChooseStore(2)">
                        </el-button>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="租赁时间" required>
                    <!--                  :picker-options="{ disabledDate }"-->
<!--                    <el-date-picker v-model="rentalTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"-->
<!--                                    :picker-options="pickerOptions"-->
<!--                                    type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"-->
<!--                                    @change="changeTime" style="width: 360px" :clearable="false">-->
<!--                    </el-date-picker>-->
                    <DateRangePicker v-model="rentalTime" @change="changeTime"></DateRangePicker>

                    <div style="color: red;font-size: 14px;" v-if="kehu.memberNo">
                      {{ cardValidity }}
                    </div>
                  </el-form-item>
<!--                  <div v-if="leaseDays" style="-->
<!--                                  line-height: 33px;-->
<!--                                  color: red;-->
<!--                                  font-weight: 600;-->
<!--                                  font-size: 16px;-->
<!--                                  display: inline-block;-->
<!--                                ">-->
<!--                    租赁时长:{{ leaseDays }}天-->
<!--                  </div>-->

                </el-col>
                <el-col :span="24">
                  <el-form-item label="品牌/车系/车型" required>
                    <div style="display: flex">
                      <el-input :value="chexing.modelInfo" placeholder="请选择车型" @click.native="clickshowchexing" readonly>
                        <el-button icon="el-icon-search" slot="append"></el-button>
                      </el-input>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>


              <el-row v-if="orderSourceCanEdit">
                <el-col :span="12">
                  <el-form-item label="订单来源" required>
                    <el-select v-model="orderSource" clearable style="width: 245px">
                      <template v-for="dict in dict.type.sys_order_source">
                        <el-option v-if="dict.value != 1 && dict.value != 3" :label="dict.label"
                                   :value="parseInt(dict.value)" :key="parseInt(dict.value)"></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>


                <el-col :span="12" v-if="orderSource > 3">
                  <el-form-item label="网络订单号">
                    <el-input v-model="networkOrderNo" placeholder="请输入网络订单号"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-else>
                <el-col :span="12">
                  <el-form-item label="订单来源" required>
                    <dict-tag :options="dict.type.sys_order_source" :value="orderSource"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="订单标签" prop="labels">
                    <el-select v-model="labels" multiple placeholder="请选择订单标签" clearable style="width: 245px">
                      <el-option v-for="item in labelList" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <template v-if="showcheliangform">
                <el-col :span="24">
                  <MmvTitle title="费用信息"></MmvTitle>
                </el-col>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="车辆押金（元）" required>
                      <el-input v-model="deposit" placeholder="请输入车辆押金"
                                @keyup.native="deposit = oninput(deposit, 2)"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="违章押金（元）" required>
                      <el-input v-model="illegalDeposit" placeholder="请输入违章押金"
                                @keyup.native="illegalDeposit = oninput(illegalDeposit, 2)"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="租车费用合计（元）" required>
                      <div style="
                                      line-height: 33px;
                                      font-weight: 600;
                                      font-size: 16px;
                                    ">¥ {{ rentTotal }} 元
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="实际租车费用（元）" required>
                      <el-input @keyup.native="rent = oninput(rent, 2)" v-model="rent" placeholder="实际租车费用"></el-input>
                    </el-form-item>

                    <span v-if="preferentialAmount > 0" style="
                                  line-height: 33px;
                                  color: red;
                                  font-weight: 600;
                                  font-size: 16px;
                                  display: inline-block;
                                ">车辆租赁费优惠金额:{{ preferentialAmount }}</span>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="23" style="margin: 0px 80px 20px 40px" class="chargeItemsVo-input">
                    <el-table :data="chargeItemsVo" border>
                      <el-table-column label="收费项名称" prop="chargeProjectName" align="center">
                        <template slot-scope="{ row }">
                          <el-input v-if="row.canEdit == 3" v-model="row.chargeProjectName"></el-input>
                          <span v-else> {{ row.chargeProjectName }} </span>
                        </template>
                      </el-table-column>

                      <el-table-column label="单价" prop="unitPrice" align="center">
                        <template slot-scope="{ row }">
                          <el-input v-model="row.unitPrice"
                                    @keyup.native="row.unitPrice = oninput(row.unitPrice, 2); jisuanMoney(row)">
                            <el-button slot="append">元</el-button>
                          </el-input>
                        </template>
                      </el-table-column>

                      <el-table-column label="收费类型" prop="chargeItemsType" align="center">
                        <template slot-scope="{ row }">
                          <el-select v-if="row.canEdit == 3" v-model="row.chargeItemsType" clearable @change="changeType(row)">
                            <el-option label="按次" :value="1"></el-option>
                            <el-option label="按天" :value="2"></el-option>
                            <el-option label="按个" :value="6"></el-option>
                          </el-select>
                          <span v-else> {{ {1: '按次', 2: '按天', 3: '按里程', 6: '按个'}[Number(row.chargeItemsType)] }}</span>

                        </template>
                      </el-table-column>

                      <el-table-column label="数目" prop="number" align="center">
                        <template slot-scope="{ row }">
                          <span v-if="row.canEdit == 1"> {{ row.number }}</span>
                          <span v-else-if="row.chargeItemsType == 2"> {{ row.number }}</span>
                          <el-input v-else v-model="row.number"
                                    @keyup.native="row.number = oninput(row.number, 0,row.upperLimitOfNumber>=0?row.upperLimitOfNumber:999999);jisuanMoney(row) "></el-input>
                        </template>
                      </el-table-column>


                      <el-table-column label="费用" prop="chargeMoney" align="center">
                        <template slot-scope="{ row }">
                          {{ Number(row.chargeMoney).toFixed(2) }} 元
                        </template>
                      </el-table-column>
                      <!--                      <el-table-column label="收费次数上限" align="center" min-width="120" prop="upperLimitOfNumber">-->
                      <!--                        <template slot-scope="scope">-->
                      <!--                          <span>{{ scope.row.upperLimitOfNumber&&scope.row.upperLimitOfNumber>=0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>-->
                      <!--                        </template>-->
                      <!--                      </el-table-column>-->
                      <!--                      <el-table-column label="收费金额上限" align="center" min-width="120" prop="upperLimitOfAmount">-->
                      <!--                        <template slot-scope="scope">-->
                      <!--                          <span>{{ scope.row.upperLimitOfAmount&&scope.row.upperLimitOfAmount>=0 ? scope.row.upperLimitOfAmount : '无上限' }}</span>-->
                      <!--                        </template>-->
                      <!--                      </el-table-column>-->
                      <el-table-column label="操作" align="center">
                        <template slot-scope="{ row }">
                          <el-button v-if="row.canEdit == 3" type="danger" icon="el-icon-delete" size="mini" @click="deleteChargingItems(row)"></el-button>
                          <el-switch v-model="row.selected" v-if="row.canEdit == 2 &&row.isOptional == 1"></el-switch>

                          <span v-if="row.isRent == 1">
                              <el-popover placement="right" trigger="click">
                                <div class="ant-popover-inner-content">
                                  <div class="fee-detail-wrapper">
                                    <div class="day-item" v-for="(item, index) in planPriceVoList" :key="index">
                                      <div class="date-weekname">
                                        <div>{{ item.time }}</div>
                                        <div>{{ item.dateOfWeek }}</div>
                                      </div>
                                      <div class="price-color word-break">¥{{ item.price }}</div>
                                    </div>
                                  </div>
                                </div>
                                <el-button slot="reference" icon="el-icon-search" type="text">价格日历</el-button>
                              </el-popover>
                            </span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>

                  <el-col :span="24" style="text-align: center;margin-bottom: 10px">
                    <el-button icon="el-icon-plus" @click="addChargingItems">添加收费项</el-button>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="费用说明">
                      <div style="display: flex">
                        <el-input v-model="moneyRemark" type="textarea" :style="{ width: '73vw' }" placeholder="请输入费用说明"
                                  :maxlength="300" show-word-limit :autosize="{ minRows: 2, maxRows: 3 }"></el-input>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>

                  <el-col :span="24">
                    <el-form-item label="支付类型" required>
                      <el-radio-group v-model.number="payType">
                        <el-radio :label="2">线下支付</el-radio>
                        <el-radio :label="1">小程序支付</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>

              <template v-if="showcheliangform && payType == 2">
                <el-row>
                  <el-col :span="24">
                    <MmvTitle title="其他信息"></MmvTitle>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="分配发车员">
                      <div style="display: flex;align-items: center;">
                        <el-input :value="nickName" placeholder="请选择人员" clearable
                                  @click.native="showfacheyuanfenpei = true;" readonly>
                          <el-button icon="el-icon-search" slot="append"></el-button>
                        </el-input>
                        <i class="el-icon-delete" style="margin-left: 10px" v-if="userId"
                           @click="nickName = null; userId = null"></i>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="分配负责人">
                      <div style="display: flex;align-items: center;">
                        <el-input :value="headName" placeholder="请选择人员" clearable
                                  @click.native="showfuzerenfenpei = true;" readonly>
                          <el-button icon="el-icon-search" slot="append"></el-button>
                        </el-input>
                        <i class="el-icon-delete" style="margin-left: 10px" v-if="headId"
                           @click="headName = null; headId = null"></i>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="分配收车员">
                      <div style="display: flex;align-items: center;">
                        <el-input :value="vehicleCollectorName" placeholder="请选择人员" clearable
                                  @click.native="showshoucheyuanfenpei = true;" readonly>
                          <el-button icon="el-icon-search" slot="append"></el-button>
                        </el-input>
                        <i class="el-icon-delete" style="margin-left: 10px" v-if="vehicleCollector"
                           @click="vehicleCollectorName = null; vehicleCollector = null"></i>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="分配车辆">
                      <div style="display: flex;align-items: center;">
                        <el-input :value="carNo" placeholder="请选择车辆" @click.native="showpeiche = true" clearable readonly>
                          <el-button icon="el-icon-search" slot="append"></el-button>
                        </el-input>
                        <i class="el-icon-delete" style="margin-left: 10px" v-if="carId"
                           @click="carId = null; carNo = null"></i>
                      </div>
                    </el-form-item>
                  </el-col>

                  <template v-if="charterService==1">

                    <el-col :span="12">
                      <el-form-item label="是否需要代驾" prop="isSubstituteDriving">
                        <el-switch
                          :active-value="1"
                          :inactive-value="2"
                          v-model="isSubstituteDriving">
                        </el-switch>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="1==isSubstituteDriving">
                      <el-form-item label="选择司机">
                        <div style="display: inline-block" @click="showDriver=!showDriver">
                          <el-input :value="substituteDrivingName" style="width: 220px; margin-right: 15px" placeholder="请选择司机"
                                    readonly>
                            <el-button icon="el-icon-search" slot="append"></el-button>
                          </el-input>
                        </div>
                      </el-form-item>
                    </el-col>

                  </template>

                  <el-col :span="12" v-if="carSource == 6">
                    <el-form-item label="托管车辆单价">
                      <div style="display: flex;align-items: center;">
                        <el-input v-model="escrowUnitPrice" placeholder="请输入单价" @keyup.native="escrowUnitPrice = oninput(escrowUnitPrice, 2)">
                          <el-button slot="append">元/天</el-button>
                        </el-input>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="订单说明" prop="remark">
                      <el-input v-model="remark" type="textarea" :style="{ width: '73vw' }" placeholder="请输入订单说明"
                                :maxlength="300" show-word-limit :autosize="{ minRows: 2, maxRows: 3 }"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row v-if="orderRemarkList.length>0" :gutter="10" type="flex" justify="center">
                  <el-col :span="6">
                    <el-button type="text" @click="handleOrderRemarkHistory">查看历史订单说明</el-button>
                  </el-col>
                </el-row>


                <el-dialog :title="'订单发车员'" :visible.sync="showfacheyuanfenpei" width="1000px" destroy-on-close
                           append-to-body @close="showfacheyuanfenpei = false">
                  <MmvDingdanfenpei ref="MmvDingdanfenpei" v-if="showfacheyuanfenpei" :reserveTakeStoreId="quchemendian.storeId" :reserveAlsoStoreId="quchemendian.storeId"
                                    @close="dingdanfenpei"></MmvDingdanfenpei>
                  <div slot="footer">
                    <el-button @click="showfacheyuanfenpei = false">关闭
                    </el-button>
                  </div>
                </el-dialog>

                <el-dialog :title="'订单收车员'" :visible.sync="showshoucheyuanfenpei" width="1000px" destroy-on-close
                           append-to-body @close="showshoucheyuanfenpei = false">
                  <MmvDingdanfenpei ref="MmvShouchefenpei" v-if="showshoucheyuanfenpei" :reserveTakeStoreId="quchemendian.storeId" :reserveAlsoStoreId="huanchemendian.storeId"
                                    @close="shouchefenpei"></MmvDingdanfenpei>
                  <div slot="footer">
                    <el-button @click="showshoucheyuanfenpei = false">关闭
                    </el-button>
                  </div>
                </el-dialog>

                <el-dialog :title="'订单负责人'" :visible.sync="showfuzerenfenpei" width="1000px" destroy-on-close
                           append-to-body @close="showfuzerenfenpei = false">
                  <MmvDingdanfenpei ref="MmvFuzerenfenpei" v-if="showfuzerenfenpei" :reserveTakeStoreId="quchemendian.storeId" :reserveAlsoStoreId="quchemendian.storeId"
                                    @close="fuzerenfenpei"></MmvDingdanfenpei>
                  <div slot="footer">
                    <el-button @click="showfuzerenfenpei = false">关闭
                    </el-button>
                  </div>
                </el-dialog>
                <el-dialog :title="'去配车'" :visible.sync="showpeiche" width="1000px" destroy-on-close append-to-body
                           @close="showpeiche = false">
                  <MmvPeiche ref="MmvPeiche" v-if="showpeiche" :modelId="chexing.modelId" :storeId="quchemendian.storeId"
                             :orderStartTime="rentalTime[0]" :orderEndTime="rentalTime[1]"
                             @close="peiche"></MmvPeiche>
                  <div slot="footer">
                    <el-button @click="showpeiche = false">关闭</el-button>
                  </div>
                </el-dialog>
              </template>
            </el-row>
          </el-form>

          <!-- 选择门店 -->
          <MmvMendian :show="showmendian" v-if="showmendian" @success="submitmendian" :all="true"></MmvMendian>
        </div>
      </template>
      <template v-slot:footer>
        <div class="footer">
          <el-button type="primary" :loading="loading" @click.native="saveForm">保存</el-button>
          <el-button type="info" plain @click.native="close">取消</el-button>
        </div>
      </template>
    </CustomContent>

    <!--  司机列表-->
    <el-dialog title="选择司机" :visible.sync="showDriver" width="1000px" destroy-on-close
               append-to-body @close="showDriver = false">
      <choose-driver ref="MmvDingdanfenpei" :storeId="quchemendian.storeId" v-if="showDriver" @success="selDriver"></choose-driver>
      <div slot="footer">
        <el-button @click="showDriver = false">关闭
        </el-button>
      </div>
    </el-dialog>
    <!--地图选点取车 -->
    <el-dialog title="地图选点" :visible.sync="positionShow" width="800px" append-to-body>
      <position :showText="false" @input="getMapInfo" :areaName="takeAddress" v-if="positionShow"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="positionShow = false">确定</el-button>
      </div>
    </el-dialog>
    <!--地图选点还车 -->
    <el-dialog title="地图选点" :visible.sync="positionShow2" width="800px" append-to-body>
      <position :showText="false" @input="getMapInfo2" :areaName="alsoAddress" v-if="positionShow2"/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="positionShow2 = false">确定
        </el-button>
      </div>
    </el-dialog>
    <!-- 选择车型 -->
    <el-dialog title="选择车型" width="1100px" destroy-on-close append-to-body :visible.sync="showchexing">
      <MmvChexing ref="MmvChexing" @checked="submitchenxing" :storeId="quchemendian.storeId" :startTime="rentalTime[0]" :orderNo="orderNo"
                  :endTime="rentalTime[1]" v-if="showchexing"></MmvChexing>
    </el-dialog>
    <!-- 选择客户 -->
    <el-dialog title="选择客户" width="1100px" destroy-on-close append-to-body :visible.sync="showkehu">
      <MmvMember ref="MmvMember" v-if="showkehu" @success="submitkehu"></MmvMember>
    </el-dialog>

    <history-order-remark ref="historyOrderRemark" :order-remark-list="orderRemarkList"></history-order-remark>

  </div>
</template>

<script>
import * as api from '@/api/order/index'
import position from '@/components/BaiduMap/baiduMapSeach.vue'
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import * as utils from '@/utils'
import MmvMember from '@/views/components/selectMember.vue'
// import MmvMendian from '@/views/store/index.vue'
import MmvMendian from '@/views/components/selectStore.vue'
import MmvKehu from '@/views/member/index.vue'
// import MmvMendian from './components/mendian.vue'
import MmvChexing from './components/chexing.vue'
import MmvAdd from '@/views/member/add'
import {addBasic, updateBasic} from '@/api/member/member'
import MmvDingdanfenpei from '@/views/order/orderBasic/dingdanfenpei'
import MmvDetail from '@/views/order/orderBasic/detail'
import MmvPeiche from '@/views/order/orderBasic/pageche'
import CustomContent from '@/components/custom/content.vue'
import {getAllLabel} from "@/api/label/label";
import Template from "@/views/system/template";
import moment from 'moment'
import {otaSyncOrders} from '@/api/ota/ctrip'
import HistoryOrderRemark from "./components/historyOrderRemark.vue";
import {validRntalTime} from "@/api/order/index";
import ChooseDriver from "./components/chooseDriver.vue"
import DateRangePicker from "@/components/DateRangePicker/index.vue";

export default {
  name: 'OrderBasicAdd',
  components: {
    DateRangePicker,
    Template,
    MmvTitle,
    MmvMendian,
    MmvMember,
    MmvChexing,
    MmvKehu,
    position,
    MmvAdd,
    MmvDingdanfenpei,
    MmvPeiche,
    CustomContent,
    HistoryOrderRemark,
    ChooseDriver
  },
  dicts: ['sys_order_source', 'sys_pay_type', 'order_payWay', 'seat', 'memberSource'],
  filters: {
    memberType(val) {
      return (
        {
          1: '企业',
          2: '个人',
        }[Number(val)] || ''
      )
    },
    memberSource(val) {
      return (
        {
          1: '搜索',
          2: '分享',
          3: '扫码',
          4: '手动录入',
        }[Number(val)] || ''
      )
    },
  },
  data() {
    return {
      aaa:"",
      bbb:"",
      ccc:null,
      pickerOptions: {
        shortcuts: [{
          text: '一天',
          onClick(picker) {
            const start = new Date();
            const end = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 );
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '两天',
          onClick(picker) {
            const start = new Date();
            const end = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 2);
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '一周',
          onClick(picker) {
            const start = new Date();
            const end = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '一月',
          onClick(picker) {
            const start = new Date();
            const end = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      takeAddressReadonly: true,
      alsoAddressReadonly: true,
      carSource: 1,//车辆来源
      escrowUnitPrice: '',//托管单价
      type: 0,//默认0 1:OTA订单单个同步
      orderNo: null,
      addOrSub: 1,
      scheduledData: {},
      showfacheyuanfenpei: false,
      showshoucheyuanfenpei: false,
      showfuzerenfenpei: false,
      fenPeiType: 1,
      showpeiche: false,
      openCustomer: false,
      submitLoading: false,
      loading: false,
      orderType: '', //订单类型
      rentalType: 1, //取车类型
      // takeStoreId: '',//取车门店
      // alsoStoreId: '',//还车门店
      rentalTime: [moment().format('YYYY-MM-DD HH:mm:ss'), moment().add(2, 'days').format('YYYY-MM-DD HH:mm:ss')], // 租赁时间
      takeAddress: '', //预约取车地址
      takeLon: '', //预约取车经度
      takeLat: '', //预约取车纬度
      alsoAddress: '', //预约还车地址
      alsoLon: '', //预约还车经度
      alsoLat: '', //预约还车纬度
      deposit: '', //押金金额
      // preferentialAmount: 0, //优惠金额/
      leaseDays: 0,
      rent: 0,
      illegalDeposit: '', //违章押金
      chargeItemsVo: [],
      planPriceVoList: [],
      labels: [],
      labelList: [],
      orderSource: 2, //订单来源
      orderSourceCanEdit: true, //订单来源
      networkOrderNo: "", //网络订单号
      payType: 2, //支付类型
      payWay: 1, //支付方式
      // 选择门店
      showmendian: false,
      mendianType: 'quchemendian',
      quchemendian: {}, // 取车门店
      huanchemendian: {}, // 还车门店
      // 选择车型
      showchexing: false,
      chexing: {}, // 车型
      modelId: null,
      myOrderNo: null,
      meal: {
        planMealId: null,
      }, // 套餐
      // 选择客户
      showkehu: false,
      kehu: {},
      // 地图选点
      positionShow: false,
      positionShow2: false,
      labelName: '',
      remark: '',
      moneyRemark: '',
      form: {
        areaName: '',
        storeLon: '', // 经度
        storeLat: '', // 纬度
      },
      userId: null,
      nickName: null,
      headId: null,
      headName: null,
      vehicleCollector: null,
      vehicleCollectorName: null,
      carId: null,
      carNo: null,
      orderRemarkList: [],

      //包车业务新增字段
      showDriver: false,
      isSubstituteDriving: 2,
      substituteDrivingId: null,
      substituteDrivingName: null,
    }
  },
  computed: {
    charterService() {
      const charterService = this.$store.state.user.charterService || 2;
      console.log('是否开启包车业务----', charterService)
      return charterService;
    },
    userInfo() {
      const userInfo = this.$store.state.user || {}
      return userInfo;
    },
    showcheliangform() {
      // 未选择门店
      if (!this.formData.takeStoreId || !this.formData.alsoStoreId) {
        return false
      }
      // 未选择租赁时间
      if (!this.formData.rentalStartTime || !this.formData.rentalEndTime) {
        return false
      }
      // 未选择车型
      if (!this.chexing.planId) {
        return false
      }
      return true
    },
    // 显示客户信息表单
    showkehuform() {
      // 未显示车辆表单
      if (!this.showcheliangform) {
        return false
      }
      // 未选择车型
      if (!this.formData.planId) {
        return false
      }
      return true
    },
    // 显示其他信息表单
    showqitaform() {
      // 未显示客户表单
      if (!this.showkehuform) {
        return false
      }
      // 未选择客户
      if (!this.formData.memberNo) {
        return false
      }
      return true
    },
    // 显示提交按钮
    showtijiaobutton() {
      if (!this.showqitaform) {
        return false
      }
      return true
    },
    // 租金合计
    rentTotal() {
      const arr = this.chargeItemsVo
      let total = 0
      arr.forEach((val) => {
        if (val.selected) {
          total += Number(val.chargeMoney)
        }
      })
      total = total > 0 ? total.toFixed(2) : 0
      this.rent = total
      return total
    },
    //
    cardValidity() {
      let str = "";
      if (!this.rentalTime[1]) {
        return str;
      }

      if (this.kehu.certificationOrder == 1) {
        if (this.kehu.cardValidity) {

          if (new Date(this.rentalTime[1]).getTime() > new Date(this.kehu.cardValidity).getTime()) {
            str += ("客户身份证件将于" + this.kehu.cardValidity + "到期  ");
          }

        } else {
          str += "无客户身份证件信息  "
        }
      }

      if (this.kehu.drivingValidity) {
        if (new Date(this.rentalTime[1]).getTime() > new Date(this.kehu.drivingValidity).getTime()) {
          str += ("客户驾驶证将于" + this.kehu.drivingValidity + "到期  ");
        }
      } else {
        str += "无客户驾驶证信息  "
      }

      return str;
    },
    // 优惠
    preferentialAmount() {
      let total = this.rentTotal - this.rent
      return total > 0 ? total.toFixed(2) : 0
    },
    formData() {
      const formData = {
        orderNo: this.orderNo,
        orderType: this.rentalType, //订单类型
        rentalType: this.rentalType, //取车类型
        takeStoreId: this.quchemendian.storeId, //取车门店
        alsoStoreId: this.huanchemendian.storeId, //还车门店
        rentalStartTime: this.rentalTime[0], //取车时间
        rentalEndTime: this.rentalTime[1], //还车时间
        leaseDays: this.leaseDays, //租期
        takeAddress: this.takeAddress, //预约取车地址
        takeLon: this.takeLon, //预约取车经度
        takeLat: this.takeLat, //预约取车纬度
        alsoAddress: this.alsoAddress, //预约还车地址
        alsoLon: this.alsoLon, //预约还车经度
        alsoLat: this.alsoLat, //预约还车纬度
        planId: this.chexing.planId, //方案id
        planMealId: this.meal.planMealId, //套餐id
        deposit: this.deposit, //押金金额
        preferentialAmount: this.preferentialAmount, //优惠金额
        rent: this.rent, //租金金额
        illegalDeposit: this.illegalDeposit, //违章押金
        memberNo: this.kehu.memberNo, //客户编号
        orderSource: this.orderSource, //订单来源
        networkOrderNo: this.networkOrderNo, //订单来源
        payType: this.payType, //支付类型
        payWay: this.payWay, //支付方式
        remark: this.remark, //订单备注
        moneyRemark: this.moneyRemark, //订单备注
        userId: this.payType == 2 ? this.userId : null, //分配用户
        vehicleCollector: this.payType == 2 ? this.vehicleCollector : null, //分配用户
        headId: this.headId,
        headName: this.headName,
        carId: this.payType == 2 ? this.carId : null, //分配车辆
        carNo: this.payType == 2 ? this.carNo : null, //分配车辆
        planPriceVoList: this.planPriceVoList, //价格日历
        labels: this.labels, //标签
        escrowUnitPrice: this.escrowUnitPrice,//托管单价
        isSubstituteDriving:this.isSubstituteDriving,//是否代驾
        substituteDrivingId:this.substituteDrivingId,//司机id
        substituteDrivingName:this.substituteDrivingName,//司机名称
      }
      formData.chargeItemsVo = this.chargeItemsVo.filter(i => {
        return i.selected && i.number > 0
      })//收费项

      return formData
    },
  },
  created() {
    this.type = this.$route.query.type || 0;
    this.orderNo = this.$route.query.orderNo;
    if (this.orderNo) {
      if (this.type == 1) {
        console.log('OTA回显');
        this.getOTADOrderData();
      } else {
        this.getData()
        console.log('系统订单回显');
      }
    }
    this.getAllLabel()
  },
  destroyed() {
  },
  methods: {
    // 选择门店
    handleChooseStore(type) {
      this.showmendian = true;
      if (type == 1) {//取车门店
        this.mendianType = 'quchemendian'
      } else if (type == 2) {//还车门店
        this.mendianType = 'huanchemendian'
      }

    },
    changeTime() {
      this.clearChexin();
      this.validRntalTime();
    },
    handleOrderRemarkHistory() {
      this.$refs.historyOrderRemark.show();
    },
    changeType(row) {
      if (row.chargeItemsType == 2) {
        row.number = this.leaseDays
        row.chargeMoney = (row.unitPrice * row.number).toFixed(2)
      } else {
        row.number = 1
        row.chargeMoney = (row.unitPrice * row.number).toFixed(2)
      }
    },
    getAllLabel() {
      getAllLabel().then((response) => {
        this.labelList = response.data
      })
    },
    dingdanfenpei(data) {
      this.userId = data.userId
      this.nickName = data.nickName
      this.showfacheyuanfenpei = false
    },
    shouchefenpei(data) {
      this.vehicleCollector = data.userId
      this.vehicleCollectorName = data.nickName
      this.showshoucheyuanfenpei = false
    },
    fuzerenfenpei(data) {
      this.headId = data.userId
      this.headName = data.nickName
      this.showfuzerenfenpei = false
    },
    peiche(data) {

      this.carId = data.carId
      this.carNo = data.carNo
      this.carSource = data.carSource
      console.log('当前车辆', data, this.carSource)
      this.showpeiche = false
    },
    // 抛出表单
    emitData() {
      if (!this.showtijiaobutton) {
        this.$message.error('表单填写未完成')
        return false;
      }

      for (let item of this.chargeItemsVo) {
        if (!item.chargeProjectName) {
          this.$message.error('费用项名称不能为空')
          return false;
        }
        if (!item.unitPrice) {
          item.unitPrice = 0
        }
        if (!item.chargeItemsType) {
          this.$message.error('请选择费用类型')
          return false;
        }
        if (!item.number) {
          item.number = 1
        }
      }
      return this.formData
    },
    /*
    |--------------------------------------------------------------------------
    | 初始化编辑订单数据
    |--------------------------------------------------------------------------
    */
    getData() {
      api.editEchoExpenseItem(this.orderNo).then(res => {
        this.chargeItemsVo = [...res.data.chargingItems]
        this.planPriceVoList = [...res.data.planPrice]
      })
      api.detail(this.orderNo).then((response) => {
        this.myOrderNo = response.data?.orderInfo.orderNo // 订单类型
        this.orderType = response.data?.orderInfo.rentalType // 订单类型
        this.rentalType = response.data?.orderInfo.rentalType // 取车类型
        this.quchemendian = {
          storeId: response.data?.orderInfo.takeStoreId, // 取车门店id
          storeName: response.data?.orderInfo.takeStoreName, // 取车门店
        }
        this.huanchemendian = {
          storeId: response.data?.orderInfo.alsoStoreId, // 还车门店id
          storeName: response.data?.orderInfo.alsoStoreName, // 还车门店
        }
        this.rentalTime = [
          response.data?.orderInfo.rentalStartTime, // 取车时间
          response.data?.orderInfo.rentalEndTime, // 还车时间
        ]
        this.takeAddress = response.data?.orderInfo.takeAddress // 预约取车地址
        this.takeLon = response.data?.orderInfo.takeLon // 预约取车经度
        this.takeLat = response.data?.orderInfo.takeLat // 预约取车纬度
        this.alsoAddress = response.data?.orderInfo.alsoAddress // 预约还车地址
        this.alsoLon = response.data?.orderInfo.alsoLon // 预约还车经度
        this.alsoLat = response.data?.orderInfo.alsoLat // 预约还车纬度
        this.modelId = response.data?.carInfo.modelId // 车型id
        // this.remark = response.data?.orderInfo.remark
        this.orderRemarkList = response.data?.orderRemarkList //订单说明列表
        this.headId = response.data?.orderInfo.headId
        this.headName = response.data?.orderInfo.headName
        this.moneyRemark = response.data?.orderInfo.moneyRemark
        this.chexing = {
          modelId: response.data?.carInfo.modelId, // 车型id
          planId: response.data?.orderInfo.planId, // 方案id
          modelInfo: response.data?.carInfo.modelName, // 车型车系
          modelName: response.data?.carInfo.modelName, // 车型车系
          carNo: response.data?.carInfo.carNo, // 车牌号
          vinNo: response.data?.carInfo.vinNo, // 车架号
          engineNo: response.data?.carInfo.engineNo, // 发动机号
          styleModel: response.data?.carInfo.styleModel, // 能源形式
          fuelType: response.data?.carInfo.fuelType, // 燃油类型
          seating: response.data?.carInfo.seating, // 车座数
          speedChangingBox: response.data?.carInfo.speedChangingBox, // 变速箱
          displacement: response.data?.carInfo.displacement, // 排量
          operatingClassification:
          response.data?.carInfo.operatingClassification, // 车辆类型
        }
        this.meal = {
          planMealId: response.data?.orderInfo.planMealId, // 需要套餐方案id去查询短租选择方案套餐
        }
        this.deposit = response.data?.orderInfo.deposit, //押金金额
          this.leaseDays = response.data?.orderInfo.leaseDays,
          this.illegalDeposit = response.data?.orderInfo.illegalDeposit, //违章押金
          this.kehu = response.data?.customerInfo || {} // 还原客户信息
        if (this.kehu.memberType == 1) {
          this.kehu.contactMember = this.kehu.memberName
          this.kehu.memberName = this.kehu.enterpriseName
        }

        this.orderSource = Number(response.data?.orderInfo.orderSource) // 订单来源
        this.orderSourceCanEdit = response.data?.orderInfo.orderSource != 1 && response.data?.orderInfo.orderSource != 3 // 订单来源
        this.networkOrderNo = response.data?.orderInfo.networkOrderNo // 网络订单号
        this.payType = Number(response.data?.orderInfo.rentPayType) // 支付类型
        this.payWay = Number(response.data?.orderInfo.rentPayWay) // 支付方式

        this.userId = response.data?.orderInfo.salesmanId
        this.nickName = response.data?.orderInfo.salesman

        this.vehicleCollector = response.data?.orderInfo.vehicleCollector
        this.vehicleCollectorName = response.data?.orderInfo.vehicleCollectorName

        this.carId = response.data?.carInfo.carId
        this.carNo = response.data?.carInfo.carNo

        this.labels = response.data.orderInfo.labels?.split(",").map(i => {
          return Number(i)
        })
        this.escrowUnitPrice = response.data?.carInfo.escrowUnitPrice
        this.carSource = response.data?.carInfo.carSource

        this.isSubstituteDriving=response.data?.orderInfo.isSubstituteDriving||2//是否代驾
          this.substituteDrivingId=response.data?.orderInfo.substituteDrivingId//司机id
          this.substituteDrivingName=response.data?.orderInfo.substituteDrivingName//司机名称

        // setTimeout(() => {
        //   this.rent = response.data?.orderInfo.rent
        // }, 300);
      })
    },

    /*
|--------------------------------------------------------------------------
| 获取OTA订单信息
|--------------------------------------------------------------------------
*/
    getOTADOrderData() {
      otaSyncOrders(this.orderNo).then((response) => {

        const orderInfo = response.data;

        this.orderType = orderInfo.orderType // 订单类型
        this.rentalType = orderInfo.rentalType // 取车类型
        this.quchemendian = {
          storeId: orderInfo.takeStoreId, // 取车门店id
          storeName: orderInfo.takeStoreName, // 取车门店
        }
        this.huanchemendian = {
          storeId: orderInfo.alsoStoreId, // 还车门店id
          storeName: orderInfo.alsoStoreName, // 还车门店
        }
        this.rentalTime = [
          orderInfo.rentalStartTime, // 取车时间
          orderInfo.rentalEndTime, // 还车时间
        ]
        this.takeAddress = orderInfo.takeAddress // 预约取车地址
        this.takeLon = orderInfo.takeLon // 预约取车经度
        this.takeLat = orderInfo.takeLat // 预约取车纬度
        this.alsoAddress = orderInfo.alsoAddress // 预约还车地址
        this.alsoLon = orderInfo.alsoLon // 预约还车经度
        this.alsoLat = orderInfo.alsoLat // 预约还车纬度
        this.modelId = orderInfo.modelId // 车型id
        this.remark = orderInfo.remark;
        this.moneyRemark = orderInfo.moneyRemark
        this.chexing = {
          modelId: orderInfo.modelId, // 车型id
          planId: orderInfo.planId, // 方案id
          modelInfo: orderInfo.modelInfo, // 车型车系
          modelName: orderInfo.modelName, // 车型车系
          carNo: orderInfo.carNo, // 车牌号
          vinNo: orderInfo.vinNo, // 车架号
          engineNo: orderInfo.engineNo, // 发动机号
          styleModel: orderInfo.styleModel, // 能源形式
          fuelType: orderInfo.fuelType, // 燃油类型
          seating: orderInfo.seating, // 车座数
          speedChangingBox: orderInfo.speedChangingBox, // 变速箱
          displacement: orderInfo.displacement, // 排量
          operatingClassification: orderInfo.operatingClassification, // 车辆类型
        }

        //TODO
        this.meal = {
          planMealId: null, // 需要套餐方案id去查询短租选择方案套餐
        }
        // 还原租金金额
        // this.submitchenxing({
        //   Moldel: this.chexing,
        //   Meal: this.meal,
        // })

        let chargeItemsVo = orderInfo.confirmationOrderVo?.chargingItemsVoList || []
        this.chargeItemsVo = [];

        for (let item of chargeItemsVo) {
          this.chargeItemsVo.push({
            ...item,
            selected: true
          })
        }

        this.deposit = orderInfo.confirmationOrderVo?.deposit, //押金金额
          this.leaseDays = orderInfo.confirmationOrderVo?.days,//租期

          this.illegalDeposit = orderInfo.confirmationOrderVo?.illegalDeposit, //违章押金

          this.kehu = {
            memberNo: orderInfo.memberNo,
            memberName: orderInfo.memberName,
            contactPhone: orderInfo.contactPhone,
            memberType: orderInfo.memberType,
            memberSource: orderInfo.memberSource,
            cardId: orderInfo.cardId,
            cardValidity: orderInfo.cardValidity,
            drivingValidity: orderInfo.drivingValidity,
            contactAddress: orderInfo.contactAddress,
            drivingId: orderInfo.drivingId,
            drivingType: orderInfo.drivingType,
            certificationOrder: orderInfo.certificationOrder
          }; // 还原客户信息


        this.orderSource = Number(orderInfo.orderSource) // 订单来源
        this.orderSourceCanEdit = orderInfo.orderSource != 1 && orderInfo.orderSource != 3 // 订单来源
        this.networkOrderNo = orderInfo.networkOrderNo // 网络订单号
        // this.payType = Number(orderInfo.rentPayType) // 支付类型
        // this.payWay = Number(orderInfo.rentPayWay) // 支付方式

        this.userId = orderInfo.userId;
        this.nickName = orderInfo.salesman;

        this.vehicleCollector = orderInfo.vehicleCollector;
        this.vehicleCollectorName = orderInfo.vehicleCollectorName;

        this.carId = orderInfo.carId;
        this.carNo = orderInfo.carNo;

        // this.labels = response.data.orderInfo.labels?.split(",").map(i => {
        //   return Number(i)
        // })
        setTimeout(() => {
          this.rent = orderInfo.confirmationOrderVo.rent
        }, 300);

        this.getPlanPriceVoList(this.chexing.planId, this.meal.planMealId);
      })
    },


    // 选择门店
    submitmendian(data) {
      this[this.mendianType] = data
      if (this.mendianType == "quchemendian") {
        this.validRntalTime();
        this.huanchemendian = this.quchemendian;
      }
      this.showmendian = false
      this.clearChexin()
    },
    //校验是否可选择
    validRntalTime() {
      if (this.quchemendian.storeId) {
        api.validRntalTime({
          takeStoreId: this.quchemendian.storeId,
          rentalStartTime: this.rentalTime[0],
          rentalEndTime: this.rentalTime[1]
        }).then(res => {
          if (res.code == 505) {
            this.$message({message: res.data, type: 'warning'})
          }
        })
      }

    },
    clearChexin() {
      this.chexing = {}
      this.meal = {}
      this.deposit = 0 // 租车押金
      this.leaseDays = 0 // 租期
      this.illegalDeposit = 0 // 违章押金
      this.chargeItemsVo = []

      this.userId = null
      this.nickName = null
      this.vehicleCollector = null
      this.vehicleCollectorName = null
      this.headId = null
      this.headName = null
      this.carId = null
      this.carNo = null
      this.substituteDrivingId = null
      this.substituteDrivingName = null
      this.isSubstituteDriving = 2
    },
    // 选择客户
    submitkehu(data) {
      // this.kehu = this.$refs?.MmvKehu?.emitData() || {};
      this.kehu = data
      this.showkehu = false
    },

    /*
    |--------------------------------------------------------------------------
    | 地图选点
    |--------------------------------------------------------------------------
    */
    getMapInfo(res) {
      this.takeLon = JSON.parse(res).lng
      this.takeLat = JSON.parse(res).lat
      this.takeAddress = JSON.parse(res).address
      this.takeAddressReadonly = false;
      this.clearChexin()
    },
    getMapInfo2(res) {
      this.alsoLon = JSON.parse(res).lng
      this.alsoLat = JSON.parse(res).lat
      this.alsoAddress = JSON.parse(res).address
      this.alsoAddressReadonly = false;
      this.clearChexin()
    },

    /*
    |--------------------------------------------------------------------------
    | 车辆信息
    |--------------------------------------------------------------------------
    */
    // 选择车型
    submitchenxing({Moldel, Meal}) {
      this.chexing = Moldel
      this.meal = Meal
      this.showchexing = false
      let endTime =
        this.meal.days > 0
          ? utils.parseTime(
            new Date(
              new Date(this.rentalTime[0]).getTime() +
              this.meal.days * 24 * 60 * 60 * 1000
            )
          )
          : this.rentalTime[1]
      this.rentalTime = [this.rentalTime[0], endTime]
      this.getconfirmationOrder(this.chexing.planId, this.meal.planMealId)
    },
    // 短租选择方案套餐
    getconfirmationOrder(planId, planMealId) {
      api.confirmationOrder({
        planId: planId, // 方案套餐id
        planMealId: planMealId, // 方案套餐id
        startTime: this.rentalTime[0], //取车时间
        endTime: this.rentalTime[1], //还车时间
        takeStoreId: this.quchemendian.storeId, //取车门店
        alsoStoreId: this.huanchemendian.storeId, //还车门店
        differentStoresCar:
          this.quchemendian.storeId == this.huanchemendian.storeId ? 2 : 1, // 跨网点还车（1.是 2.否）
        rentalType: this.rentalType, //取车类型
        takeLat: this.takeLat, //取车经度
        takeLon: this.takeLon, //取车纬度
        alsoLat: this.alsoLat, //还车经度
        alsoLon: this.alsoLon, //还车纬度
      })
        .then((response) => {
          this.deposit = response.data?.deposit || 0 // 租车押金
          this.leaseDays = response.data?.days || 0 // 租期

          this.planPriceVoList = response.data?.planPriceVoList || []//价格日历

          this.illegalDeposit = response.data?.illegalDeposit || 0 // 违章押金
          const chargingItemsVoList = response.data?.chargingItemsVoList || [] // 上门 取车 还车 异店 费用
          const noMandatoryOtherCostList = response.data?.noMandatoryOtherCostList || [] // 其他费用—非必选
          const requiredInsurance = response.data?.requiredInsurance || [] // 其他费用—必选保险
          const noRequiredInsurance = response.data?.noRequiredInsurance || [] // 其他费用—非必选保险
          let chargeItemsVo = [...chargingItemsVoList, ...noMandatoryOtherCostList, ...requiredInsurance, ...noRequiredInsurance]
          this.chargeItemsVo = [];
          for (let item of chargeItemsVo) {
            this.chargeItemsVo.push({
              ...item,
              selected: item.canEdit !== 2 || item.isOptional !== 1,
              number: item.number > 0 ? item.number : 1,
              chargeMoney: item.number > 0 ? item.chargeMoney : item.unitPrice
            })
          }

        })
    },
    // 价格日历
    getPlanPriceVoList: function (planId, planMealId) {
      api.confirmationOrder({
        planId: planId, // 方案套餐id
        planMealId: planMealId, // 方案套餐id
        startTime: this.rentalTime[0], //取车时间
        endTime: this.rentalTime[1], //还车时间
        takeStoreId: this.quchemendian.storeId, //取车门店
        alsoStoreId: this.huanchemendian.storeId, //还车门店
        differentStoresCar: this.quchemendian.storeId == this.huanchemendian.storeId ? 2 : 1, // 跨网点还车（1.是 2.否）
        rentalType: this.rentalType, //取车类型
        takeLat: this.takeLat, //取车经度
        takeLon: this.takeLon, //取车纬度
        alsoLat: this.alsoLat, //还车经度
        alsoLon: this.alsoLon, //还车纬度
      })
        .then((response) => {
          this.planPriceVoList = response.data?.planPriceVoList || []//价格日历

          // const chargingItemsVoList = response.data?.chargingItemsVoList || [] // 上门 取车 还车 异店 费用
          // const noMandatoryOtherCostList = response.data?.noMandatoryOtherCostList || [] // 其他费用—非必选
          // const requiredInsurance = response.data?.requiredInsurance || [] // 其他费用—必选保险
          // const noRequiredInsurance = response.data?.noRequiredInsurance || [] // 其他费用—非必选保险
          // let chargeItemsVo = [...noMandatoryOtherCostList,...requiredInsurance,...noRequiredInsurance]
          // let names = this.chargeItemsVo.map(item => {
          //   return item.chargeProjectName
          // })
          // for (let item of chargeItemsVo) {
          //   if(!names.includes(item.chargeProjectName)){
          //     item.selected=false
          //     this.chargeItemsVo.push(item)
          //   }
          // }

        })
    },
    addChargingItems() {
      this.chargeItemsVo.push({
        chargeProjectName: '',
        unitPrice: 0,
        chargeItemsType: 1,
        chargeProjectCategory: 9,
        number: 1,
        canEdit: 3,
        chargeMoney: 0,
        selected: true
      })
    },
    deleteChargingItems(row) {
      let _index = -1;
      this.chargeItemsVo.forEach((item, index) => {
        if (row.chargeProjectName == item.chargeProjectName && item.canEdit == 3) {
          _index = index
        }
      })
      this.chargeItemsVo.splice(_index, 1)
    },
    jisuanMoney(row) {
      let chargeMoney = (row.unitPrice * row.number) || 0;
      if (row.upperLimitOfAmount != null && row.upperLimitOfAmount >= 0 && chargeMoney > row.upperLimitOfAmount) {
        row.chargeMoney = row.upperLimitOfAmount.toFixed(2);
      } else {
        row.chargeMoney = chargeMoney.toFixed(2);
      }
    },
    //选择司机
    selDriver(data) {
      console.log('选择了 司机', data)
      this.showDriver = false
      this.substituteDrivingName = data.nickName
      this.substituteDrivingId = data.userId
    },
    /*
    |--------------------------------------------------------------------------
    | 时间禁用处理
    |--------------------------------------------------------------------------
    */
    disabledDate(date) {
      return (
        new Date().getTime() >= new Date(date).getTime() + 24 * 60 * 60 * 1000
      )
    },
    /** 提交订单 */
    saveForm() {
      const form = this.emitData()
      if (!form) {
        return;
      } else {
        this.loading = true
        if (this.type == 1) {//OTA订单同步新增
          form.orderNo = null;
          api.add(form).then((response) => {
            this.scheduledData = response.data
            this.$modal.msgSuccess('新增日租订单成功')
            this.close()
          }).finally(r => {
            this.loading = false
          })

        } else {//编辑或新增
          if (form.orderNo) {
            api.put(form).then((response) => {
              this.scheduledData = response.data
              this.$modal.msgSuccess('修改日租订单成功')
              this.close()
            }).finally(r => {
              this.loading = false
            })
          } else {
            form.myOrderNo = this.myOrderNo;
            api.add(form).then((response) => {
              this.scheduledData = response.data
              this.$modal.msgSuccess('新增日租订单成功')
              this.close()
            }).finally(r => {
              this.loading = false
            })
          }
        }

      }

    },
    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    /** 提交按钮 */
    submitForm() {
      try {
        this.submitLoading = true
        this.$refs['MmvAdd'].validate().then((valid) => {
          if (valid) {
            const form = this.$refs['MmvAdd'].emitData()
            addBasic(form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.openCustomer = false
              this.kehu = response.data
              this.submitLoading = false
            })
          }
        })
      } catch (error) {
        this.submitLoading = false
        this.$message.error(error.message)
      }
      //     }
      // });
      setTimeout(() => {
        this.submitLoading = false
      }, 2e3)
    },
    clickshowchexing() {
      if (!this.quchemendian.storeName) {
        this.$message.error('请选择取车门店')
        return;
      }
      if (!this.huanchemendian.storeName) {
        this.$message.error('请选择还车门店')
        return;
      }
      if (this.rentalTime.length == 0) {
        this.$message.error('请选择租赁时间')
        return;
      }
      this.showchexing = true
      // api.classificationMoldelList({
      //   storeId: this.quchemendian.storeId,
      //   startTime: this.rentalTime[0],
      //   endTime: this.rentalTime[1],
      //   order:this.orderNo,
      //   pageNum: 1
      // }).then((res) => {
      //   if (res.rows.length == 0) {
      //     this.$message.error('未查询到已设置车价且启用中的车型')
      //     return;
      //   }
      //   this.showchexing = true
      // })
    }
  },
}
</script>
<style scoped>
.fee-detail-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 420px;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  max-height: 400px;
  overflow-y: auto;
}

.day-item {
  width: 80px;
  text-align: center;
  margin-top: 10px;
}

.price-color {
  color: #ff8b26;
}

::v-deep .chargeItemsVo-input .el-input__inner {
  text-align: center;
}
</style>
